package top.kiterunner.learning.concurrency_test;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/3.
 */
public class ThreadDemo0 {

    private int count = 0;
    private static int scount = 0;
    private Object lock = new Object();

    public void incrementCount_v1() {
        // 任何线程要执行下面的代码，必须先获取lock的锁
        synchronized (lock) {
            count++;
            System.out.println(Thread.currentThread().getName() + " Count = " + count);
        }
    }

    public void incrementCount_v2() {
        // 任何线程要执行下面的代码，必须先获取this的锁
        synchronized (this) {
            count++;
            System.out.println(Thread.currentThread().getName() + " Count = " + count);
        }
    }

    // 该版本等同于版本二，注意synchronzied锁定的是对象，而不是代码段
    public synchronized void incrementCount_v3() {
        count++;
        System.out.println(Thread.currentThread().getName() + " Count = " + count);
    }

    public synchronized static void staticIncrementCount_v1() {
        scount++;
        System.out.println(Thread.currentThread().getName() + " Count = " + scount);
    }

    public static void staticIncrementCount_v2() {
        // 当锁定一个静态方法时，一般锁定的是Class对象
        synchronized (ThreadDemo0.class) {
            scount++;
            System.out.println(Thread.currentThread().getName() + " Count = " + scount);
        }
    }
}
